package com.example.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

import java.security.Principal;

@Controller
public class WebSocketController {

    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    @MessageMapping("/hello")
    @SendTo("/topic/greetings")
    public String greeting(String message) throws Exception {
        // 处理收到的消息并广播到订阅的客户端
        return "Hello, " + message + "!";
    }

    @MessageMapping("/IP")
    @SendTo("/topic/IP2")
    public String ip(String message) throws Exception {
        // 处理收到的消息并广播到订阅的客户端
        return message;
    }

    @MessageMapping("/sendMessage")
    public void sendMessage(String message, Principal principal) {
        String recipient = principal.getName(); // 获取接收者的用户名
        // 处理消息的逻辑

        messagingTemplate.convertAndSendToUser(recipient, "/queue/myQueue", message);
    }
}
